<!-- 用户资金流水列表 -->
<template>
    <div class="pageListBox">
        <div class="cardAdmin">
            <div class="formNewAdmin" v-if="formshow">
                <div class="formSearch">
                    <span class="namename">用户名</span>
                    <el-input size="mini" style="flex: 3" v-model="form.username"></el-input>
                </div>
                <div class="formSearch">
                    <span class="namename">交易类型</span>

                    <el-select style="flex: 3" v-model="form.transaction_type" placeholder="请选择交易类型" size="mini">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>

                <div class="souSuoYouCe">
                    <el-button icon="el-icon-refresh" size="mini" class="white-button" @click="resetForm()">重置</el-button>
                    <el-button class="black-button" icon="el-icon-search" size="mini" @click="get_data('btn')">搜索</el-button>
                </div>
            </div>
        </div>
        <div class="btnBoxList">
            <div class="btns">
                <!-- <el-button class="green-button" size="mini" icon="el-icon-plus" plain @click="addbtn()">Add</el-button> -->
                <el-button class="black-button" size="mini" icon="el-icon-refresh" plain
                    @click="get_data()">刷新表格</el-button>
            </div>
            <div class="formbtns">
                <div style="max-width: 200px;height: 100%;;background-color: #f4f4f4;display: flex;">
                    <div class="poipoi1">
                        <el-dropdown @command="exportTable" class="popo1cli" trigger="click" placement="bottom">
                            <span class="el-dropdown-link">
                                <i style="font-size: 18px;" class="el-icon-download"></i>
                                <i style="font-size: 14px;" class="el-icon-caret-bottom"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="json">JSON</el-dropdown-item>
                                <el-dropdown-item command="xml">XML</el-dropdown-item>
                                <el-dropdown-item command="csv">CSV</el-dropdown-item>
                                <el-dropdown-item command="txt">TXT</el-dropdown-item>
                                <el-dropdown-item command="word">Word</el-dropdown-item>
                                <el-dropdown-item command="excel">Excel</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <div class="poipoi2">
                        <i style="font-size: 18px;cursor: pointer;" class=" el-icon-search" @click="showform"></i>

                    </div>
                </div>
            </div>
        </div>
        <!-- 表格 -->
        <el-table v-table-resize  border highlight-current-row :data="tableData" cell-class-name="rowlist" class="x1919" ref="tableRef" size="mini"
            v-loading="table_loading">
            <el-table-column prop="id" fixed="left"  label="ID" width="auto" align="center" min-width="80px">
            </el-table-column>
            <el-table-column prop="username" label="用户名" width="auto" align="center" min-width="140px">
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="auto" align="center" min-width="120px">
            </el-table-column>
            <el-table-column prop="fund_type" label="资金类型" width="auto" align="center" min-width="120px">
            </el-table-column>
            <el-table-column prop="transaction_type" label="交易类型" align="center" min-width="120px">
                <template slot-scope="scope">
                    <span v-if="scope.row.transaction_type === 'recharge'">充值</span>
                    <span v-else-if="scope.row.transaction_type === 'withdrawal'">提现</span>
                    <span v-else-if="scope.row.transaction_type === 'coupon'">优惠券发放</span>
                    <span v-else-if="scope.row.transaction_type === 'buyback'">回购</span>
                    <span v-else-if="scope.row.transaction_type === 'adjustment'">手动调整</span>
                    <span v-else-if="scope.row.transaction_type === 'subscribe'">订阅</span>
                    <span v-else>{{ scope.row.transaction_type }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="auto" align="center" min-width="120px">
            </el-table-column>
            <el-table-column prop="user_id" label="用户ID" width="auto" align="center" min-width="80px">
            </el-table-column>

            <el-table-column prop="add_time" label="添加时间" width="auto" align="center" min-width="150px">
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
                <template slot-scope="scope">
                    <el-button @click="tableEditing(scope.row)" class="green-button"
                        icon="el-icon-edit" type="info" plain size="mini"></el-button>

                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="fenye11">
            <div style="display: flex;align-items: center;">{{ `当前第 ${currentPage} 页，每页 ${pagesize} 条记录` }}</div>
            <el-pagination background layout="prev, pager, next,total" :total="total" :page-size="pagesize"
                @current-change="current_change"></el-pagination>
        </div>
        <!-- 弹窗 -->
        <el-dialog :close-on-click-modal="false" title="新增" top="5vh" :visible.sync="dialogVisibleAdd" 
            :before-close="beforeClose">
            <el-form :model="formAdd" :rules="rulesAdd" ref="formAdd" class="demo-formAdd">
                <el-form-item>
                    <el-switch active-color="#18bc9c" v-model="formAdd.status" :active-value="1" :inactive-value="0"
                        inactive-color="#ccc" active-text="启用" inactive-text="禁用">
                    </el-switch>
                </el-form-item>
                <el-form-item label="交易类型" prop="group_name">
                    <el-input size="mini" v-model="formAdd.type"></el-input>
                </el-form-item>
                <el-divider></el-divider>
                <el-form-item class="fbtns">
                    <el-button class="purple-button" size="mini" @click="add_data" :loading="btnAdd" plain>确认新增</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog v-dialog-drag :close-on-click-modal="false" top="90px" title="更新" :visible.sync="dialogVisibleEdit"
             v-loading="dialogVisibleEditLoading" :before-close="beforeClose">
            <el-form :model="formEdit" :rules="rulesEdit" ref="formEdit" class="demo-formEdit">
                <el-form-item label="用户名" prop="username">
                    <el-input disabled size="mini" v-model="formEdit.username"></el-input>
                </el-form-item>
                <el-form-item label="金额" prop="amount">
                    <el-input type="number" size="mini" v-model="formEdit.amount"></el-input>
                </el-form-item>
                <el-form-item label="资金类型" prop="fund_type">
                    <el-input size="mini" v-model="formEdit.fund_type"></el-input>
                </el-form-item>
                <el-form-item label="交易类型" prop="transaction_type">
                    <el-select style="width: 100%;" v-model="formEdit.transaction_type" placeholder="请选择交易类型" size="mini">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input size="mini" v-model="formEdit.remark"></el-input>
                </el-form-item>

            </el-form>
            <template slot="footer">
                <div class="fbtns">
                    <el-button class="black-button" size="mini" plain @click="upd_data" :loading="btnEdit">确认修改</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script>
import {
    user_fund_flow_list,
    user_fund_flow_editing,
    user_group_addition,
    user_group_deletion,
} from "@/utils/api";
export default {
    name: "userFundFlow",

    data() {
        return {
            table_loading: true,
            touristsspeak: [
                {
                    value: 1,
                    label: "是",
                },
                {
                    value: 0,
                    label: "否",
                },
            ],
            dialogVisibleEditLoading: false,
            dialogVisibleEdit: false,
            btnAdd: false,
            btnEdit: false,
            formshow: false,
            exportFormat: '',
            // 下拉框选中的列（存储 prop 值）
            selectedColumns: ['name'], // 默认选中姓名和日期

            // 所有可选的列配置
            allColumns: [
                { prop: 'last_login_time', label: '最后登录时间', width: '140px' }
            ],
            pagesize: 10,
            total: 0,
            options: [
                {
                    value: 'recharge',
                    label: "充值",
                },
                {
                    value: 'withdrawal',
                    label: "提现",
                },
                {
                    value: 'coupon',
                    label: "优惠券发放",
                },
                {
                    value: 'buyback',
                    label: "回购",
                },
                {
                    value: 'adjustment',
                    label: "资金调整",
                },
            ],
            defaultProps: {
                children: "childs",
                label: "name",
            },
            menuProps: {
                children: "children",
                label: "label",
            },
            formAdd: {
                group_name: '',
                permissions: '',
                status: 0,

            },
            formEdit: {
                id: '',
                username: '',
                amount: '',
                fund_type: '',
                remark: '',
                transaction_type: '',


            },
            form: {
                username: "",
                transaction_type: "",

            },
            tableData: [
                { id: 1, date: '2023-01-01', group_name: '张三', status: '北京', permissions: '13800138000', name: 'name' },
                { id: 2, date: '2023-01-02', group_name: '李四', status: '上海', permissions: '13900139000', name: 'name' },
            ],
            dialogVisibleAdd: false,
            titles: "",
            name: "",
            nametype: "编辑",
            expandedKeys: [], // 控制哪些行默认展开
            menuData: [], //菜单列表
            userRoleList: [], //角色列表
            articlmenu: [], //文章列表
            draftsmenu: [], //草稿箱列表
            currentNodeData: [],
            currentDraftsKey: [],
            currentPage: 1,
            rulesEdit: {
                amount: [
                    { required: true, message: "请输入金额", trigger: "blur" },
                ],
                fund_type: [
                    { required: true, message: "请输入资金类型", trigger: "blur" },
                ],
                remark: [
                    { required: true, message: "请输入备注", trigger: "blur" },
                ],
                transaction_type: [
                    { required: true, message: "请输入交易类型", trigger: "blur" },
                ],

            },
            rulesAdd: {
                group_name: [
                    { required: true, message: "请输入分组名称", trigger: "blur" },
                ],
                permissions: [
                    { required: true, message: "请分配权限", trigger: "blur" },
                ],
            },
        };
    },
    computed: {
        userRoleId() {
            const user = JSON.parse(localStorage.getItem("user"));
            return user ? user.role_id : null;
        },
        // 计算实际要显示的列
        visibleColumns() {
            return this.allColumns.filter(col =>
                this.selectedColumns.includes(col.prop)
            )
        }
    },
    watch: {
        // 当选择的列变化时，可以在这里添加额外逻辑
        selectedColumns(newVal) {
            console.log('当前显示的列：', newVal)
        },
    },
    mounted() {
        this.get_data();
    },

    methods: {
        setCheckedKeys(permissionIds) {
            console.log(permissionIds);
            if (!permissionIds) return;

            // 将字符串转换为数字数组
            const idsArray = permissionIds.split(',')
                .map(id => parseInt(id.trim()))
                .filter(id => !isNaN(id));

            if (idsArray.length > 0) {
                this.$refs.permissionTreeEdit.setCheckedKeys(idsArray);
            }
        },
        showform() {
            this.formshow = !this.formshow
        },
        get_time() {
            const now = new Date();
            const formatted = now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + ' ' +
                String(now.getHours()).padStart(2, '0') + ':' +
                String(now.getMinutes()).padStart(2, '0') + ':' +
                String(now.getSeconds()).padStart(2, '0');
            return formatted
        },
        // 新增打开
        addbtn() {
            this.dialogVisibleAdd = true;
            this.titles = "新增";
        },
        // 查询
        async get_data(btn) {
            if (btn) this.currentPage = 1
            this.table_loading = true; // 开始加载

            let params = new URLSearchParams();

            params.append('page', this.currentPage);
            params.append('page_size', this.pagesize);

            if (this.form.username) params.append('username', this.form.username);
            if (this.form.transaction_type) params.append('transaction_type', this.form.transaction_type);


            let data = `?${params.toString()}`;

            try {
                const res = await user_fund_flow_list(data);
                if (res.data && res.data.code == "200") {


                    this.tableData = res.data.data.data;
                    this.total = res.data.data.total_records;
                } else {
                    this.$message.error(res?.data?.msg || "获取数据失败");
                }
            } catch (err) {
                console.error("获取数据失败:", err);
                this.$message.error("请求出错，请稍后再试");
            } finally {
                this.table_loading = false; // 不论成功失败都结束 table_loading
            }
        },
        // 新增
        async add_data() {

            this.btnAdd = true;
            try {
                const valid = await this.$refs.formAdd.validate();
                if (!valid) {
                    this.$message.warning("表单验证未通过");
                    return;
                }

                const fields = [
                    'group_name', 'status'
                ];

                let data = {};

                for (const key of fields) {
                    const value = this.formAdd[key];
                    if (value !== '' && value !== null && value !== undefined) {
                        data[key] = value;
                    }
                }


                const res = await user_group_addition(data);
                console.log(res, '新增');
                if (res && res.status == "200" && res.data.code == "200") {
                    // this.$message.success(res.data.message);

                    this.$notify({
                        title: `${res.data.message}`,
                        message: `ID:${res.data.data.id}`,
                        type: 'success',
                        duration: 8000,
                        position: 'bottom-right'
                    });
                    this.get_data();
                    this.dialogVisibleAdd = false;
                } else {
                    this.$message.error(res?.data?.message || "操作失败");
                }
            } catch (err) {
                console.error(err);
                this.$message.error("请求失败，请稍后再试");
            } finally {
                this.btnAdd = false;
            }
        },
        // 更新
        async upd_data() {
            this.btnEdit = true;
            try {
                const valid = await this.$refs.formEdit.validate();
                if (!valid) {
                    this.$message.warning("表单验证未通过");
                    return;
                }
                const id = this.formEdit.id
                const fields = [
                    'amount', 'fund_type', 'remark', 'transaction_type'
                ];

                const data = {};
                for (const key of fields) {
                    const value = this.formEdit[key];
                    if (value !== '' && value !== null && value !== undefined) {

                        if (data[key] === 'amount') {
                            data[key] = Number(value);
                        } else {
                            data[key] = value;
                        }
                    }
                }

                const response = await user_fund_flow_editing(id, data);

                if (response.data && response.data.code == "200") {
                    this.$message.success(response.data.msg);
                    this.dialogVisibleEdit = false;
                    this.get_data();
                } else {
                    this.$message.warning(response?.data?.msg || "操作失败");
                }
            } catch (err) {
                console.error("更新失败:", err);
                this.$message.error("请求出错，请稍后再试");
            } finally {
                this.btnEdit = false;
            }
        },
        // 删除
        async del_data(id) {
            try {
                await this.$confirm("是否继续执行操作？", "提示", {
                    confirmButtonText: "是",
                    cancelButtonText: "否",
                    type: "warning",
                });

                const res = await user_group_deletion(id).catch((err) => {
                    return console.error(err);
                });

                if (res && res.status == "200" && res.data.code == "200") {
                    this.$message.success(res.data.msg);
                    this.dialogVisibleAdd = false;
                    this.get_data();
                } else {
                    this.$message.error(res.data.msg);
                }
            } catch (error) {
                // 用户点击取消或关闭对话框
                console.error(error);
            }
        },
        // 关闭弹窗
        beforeClose() {
            this.dialogVisibleEdit = false
            this.dialogVisibleAdd = false

            this.formAdd = {
            }
            this.formEdit = {
                id: '',
                username: '',
                amount: '',
                fund_type: '',
                remark: '',
                transaction_type: '',
            }
        },

        // 分页
        current_change(currentPage) {
            this.currentPage = currentPage;
            this.get_data();
        },
        // 重置
        resetForm() {
            this.form = {
                username: ""
            };
            this.currentPage = 1;
            this.get_data();
        },
        // 编辑打开
        tableEditing(row) {
            this.titles = "编辑";
            this.dialogVisibleEdit = true;

            this.formEdit.id = row.id;

            this.formEdit.username = row.username


            this.formEdit.amount = Number(row.amount)
            this.formEdit.fund_type = row.fund_type
            this.formEdit.remark = row.remark
            this.formEdit.transaction_type = row.transaction_type

        },
        exportTable(format) {
            switch (format) {
                case 'json':
                    this.exportJSON();
                    break;
                case 'xml':
                    this.exportXML();
                    break;
                case 'csv':
                    this.exportCSV();
                    break;
                case 'txt':
                    this.exportTXT();
                    break;
                case 'word':
                    this.exportWord();
                    break;
                case 'excel':
                    this.exportExcel();
                    break;
            }
        },
        exportJSON() {
            const jsonStr = JSON.stringify(this.tableData, null, 2);
            const blob = new Blob([jsonStr], { type: 'application/json' });
            this.downloadBlob(blob, 'table.json');
        },
        exportXML() {
            const xml = `<?xml version="1.0"?>\n<rows>\n` +
                this.tableData.map(item =>
                    `  <row>\n` +
                    `    <id>${item.id}</id>\n` +
                    `    <username>${item.username}</username>\n` +
                    `    <amount>${item.amount}</amount>\n` +
                    `    <fund_type>${item.fund_type}</fund_type>\n` +
                    `    <transaction_type>${item.transaction_type}</transaction_type>\n` +
                    `    <remark>${item.remark}</remark>\n` +
                    `  </row>`).join('\n') +
                `\n</rows>`;
            const blob = new Blob([xml], { type: 'application/xml' });
            this.downloadBlob(blob, 'table.xml');
        },
        exportCSV() {
            const headers = ['ID', '用户名', '金额', '资金类型', '交易类型', '备注'];
            const rows = this.tableData.map(item => [item.id, item.username, item.amount, item.fund_type, item.transaction_type, item.remark]);
            let content = headers.join(',') + '\n';
            rows.forEach(row => {
                content += row.join(',') + '\n';
            });
            const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
            this.downloadBlob(blob, 'table.csv');
        },
        exportTXT() {
            const headers = ['ID', '用户名', '金额', '资金类型', '交易类型', '备注'];
            const rows = this.tableData.map(item => [item.id, item.username, item.amount, item.fund_type, item.transaction_type, item.remark]);
            let content = headers.join('\t') + '\n';
            rows.forEach(row => {
                content += row.join('\t') + '\n';
            });
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8;' });
            this.downloadBlob(blob, 'table.txt');
        },
        async exportWord() {
            const { default: HTMLDocx } = await import('html-docx-js/dist/html-docx');
            const html =
                `<table border="1" cellpadding="5" cellspacing="0"><tr><th>ID</th><th>用户名</th><th>金额</th><th>资金类型</th><th>交易类型</th><th>备注</th></tr>` +
                this.tableData.map(item =>
                    `<tr><td>${item.id}</td><td>${item.username}</td><td>${item.amount}</td><td>${item.fund_type}</td><td>${item.transaction_type}</td><td>${item.remark}</td></tr>`
                ).join('') +
                `</table>`;
            const blob = HTMLDocx.asBlob(html);
            this.downloadBlob(blob, 'table.docx');
        },
        async exportExcel() {
            const XLSX = await import('xlsx');
            const ws = XLSX.utils.json_to_sheet(this.tableData);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
            const blob = new Blob([wbout], { type: 'application/octet-stream' });
            this.downloadBlob(blob, 'table.xlsx');
        },
        downloadBlob(blob, filename) {
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            link.click();
            URL.revokeObjectURL(link.href);
        }
    },
};
</script>
<style>
.rowlist {
    padding: 6px !important;
}

.nbysm {
    flex: 2;
    text-align: right;
    line-height: 40px;
    font-weight: 700;
    font-size: 15px;
}

.souSuoYouCe {
    margin: 20px 0 0 auto;
    padding-bottom: 5px;
    padding-right: 10px;
}

.cell {
    font-size: 13px;
    white-space: nowrap !important;
}

.demo-table-expand {
    font-size: 0;
    margin-left: 10px;
}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
</style>
<style lang="less" scoped>
.namename {
    padding: 0 10px;
    text-align: right;
    line-height: 40px;
    font-weight: 700;
    font-size: 15px;
    display: flex;
    align-items: center;
}

.el-textarea {
    overflow: hidden;
    /* 隐藏滚动条 */
}

.pageListBox {
    width: 100%;
    // padding: 10px;
    // background-color: aquamarine;
    height: auto;
    // border: 1px #000 solid;

    .cardAdmin {
        position: relative;
        // height: 18%;
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        margin: 0;

        // border: #fafafa solid 1px;
        padding: 0 5px;
        margin-bottom: 2px;

        .formNewAdmin {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            padding: 0;
            align-self: baseline;
            padding-bottom: 10px;
            border-bottom: 1px #e3e3e3 solid;
        }

        .formSearch {
            width: 25%;
            min-width: 25%;
            margin-top: 20px;
            height: 30px;
            display: flex;
            justify-content: center;
        }
    }

    .btnBoxList {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;

        .formbtns {
            width: 50%;
            display: flex;
            justify-content: end;
            padding: 5px 10px;

            .qweqweasdasd {
                width: 75px;
                padding: 5px 10px;
                border: 1px #f4f4f4 solid;
            }

            .qweqweasdasd:hover {

                background-color: #e7e7e7;
                border: 1px #ccc solid;
            }


            .btnList22 {
                width: auto;
                height: 28px;
                color: #000;
                min-width: 50px;
                border-radius: 0px;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;

                i {
                    font-size: 18px;
                }
            }

        }

        .btns {
            width: 50%;
            display: flex;
            padding: 5px 10px;



        }


    }

    .pop-up-form {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        padding: 0;
        align-self: baseline;
        margin: 10px 0;
        justify-content: center;
        padding-right: 15px;

        .form-options {
            width: 100%;
            min-width: 100%;
            height: 40px;
            display: flex;
            justify-content: center;
            margin: 10px 0;
        }
    }
}
</style>
<style lang="less">
.cell {
    font-size: 13px;
    white-space: nowrap !important;
}

textarea {
    resize: none !important;
}

/* 子级样式 */
.child-row11 {
    background-color: #fcfcfc !important;
    color: #ff8718;
}

/* 父级样式 */
.parent-row11 {
    background-color: #ffffff;
    color: #000;
    font-weight: 500;
}

.parent-row11 .cell {
    font-size: 13px !important;
}

.el-dropdown-link {
    height: 100%;
    cursor: pointer;
    color: #000;
    font-weight: bold;
    font-size: 14px;
    display: flex;
    align-items: center;
}

.fenye11 {
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    padding: 4px 8px;
}



.el-pager li.active {
    background-color: #000 !important;
}

.setFomr {
    display: flex;
    align-items: center;
    padding: 10px 10px 0 10px;
}




.resetForm-button {
    background-color: #ffffff !important;
    border-color: #333 !important;
    color: #333 !important;
    font-size: 13px !important;
}

.resetForm-button:hover {
    background-color: #fff !important;
    border-color: #333 !important;
}

.switchitem {
    display: flex;
    justify-content: space-between;
    align-items: center;

    label {
        text-align: left;
    }

}

.switchitem::after,
.switchitem::before {
    display: none !important;
}
</style>
  